package com.ruoyi.graph.service.impl;


import com.ruoyi.graph.dao.RelationshipDao;
import com.ruoyi.graph.dao.TableDao;
import com.ruoyi.graph.domain.Relationship;
import com.ruoyi.graph.domain.TableNode;
import com.ruoyi.graph.domain.dto.TableNodeDTO;
import com.ruoyi.graph.domain.vo.TabelNodeRelationVO;
import com.ruoyi.graph.domain.vo.RelationshipVo;
import com.ruoyi.graph.service.TableNodeService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;


@Slf4j
@Service
public class TableNodeServiceImpl implements TableNodeService {

    @Autowired
    private TableDao tableDao;
    @Autowired
    private RelationshipDao relationshipDao;

    @Override
    public void addNode(TableNode tableNode) {

        tableDao.save(tableNode);
    }

    @Override
    public TableNode getNode(TableNode tableNode) {
        // 根据库名和表名查询节点
        return tableDao.findByName(tableNode.getDatabase(),tableNode.getTableName());
    }

    @Override
    public void deleteNode(TableNodeDTO tableNodeDto) {

        TableNode tableNode = new TableNode(tableNodeDto.getDatabase(),tableNodeDto.getTableName());
        tableDao.delete(tableNode);
    }


    @Override
    public List<Relationship> getAllNodes() {

        return tableDao.getAllNodes();
    }

    @Override
    public TabelNodeRelationVO getAllNodesByName(TableNode tableNode) {
        TabelNodeRelationVO all = new TabelNodeRelationVO();

        List<TableNode> upResult = tableDao.findAllUpAndDownStream(tableNode.getTableName(),tableNode.getDatabase());
        List<Relationship> downRelation = relationshipDao.findAllRelationStream(tableNode.getTableName(),tableNode.getDatabase());
        if(downRelation!=null&&downRelation.size()>0){
            List<RelationshipVo> shipVos = new ArrayList<>();
            downRelation.forEach(s->{
                RelationshipVo ship = new RelationshipVo();
                ship.setUuid(s.getId());
                ship.setSourceId(s.getStartNode().getId());
                ship.setTargetId(s.getEndNode().getId());
                shipVos.add(ship);
            });
            all.setRelationship(shipVos);
        }
        if(upResult!=null&&upResult.size()>0) {
            all.setNode(upResult);
        }

        return all;
    }


}
